<template>
  <div>
    <div class="breadcrumb_wrap">
      <span class="current">当前位置：</span>
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/personalcenter' }">个人中心</el-breadcrumb-item>
        <el-breadcrumb-item>资料中心</el-breadcrumb-item>
        <el-breadcrumb-item>账号绑定</el-breadcrumb-item>
      </el-breadcrumb>
      <el-button style="position: absolute; right: 10px; top: 5px" type="primary" plain size="small"
                 @click="toDoctorCertify">医生认证</el-button>
    </div>

    <div class="account_card">
      <div class="account_item">
        <div class="account_item_line">
          <div class="account_item_left">
            <i class="el-icon-message account_icon"></i>
            <span class="account_title">邮箱绑定</span>
          </div>
        </div>
        <div class="email_form_wrap">
          <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px"
                   class="demo-ruleForm">
            <el-form-item label="手机号" prop="phonenumber">
              <el-input v-model="ruleForm.phonenumber"></el-input>
            </el-form-item>
            <el-form-item label="要修改的邮箱" prop="email">
              <el-input v-model="ruleForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机验证码" prop="phonecode">
              <el-input v-model="ruleForm.phonecode"></el-input>
              <el-button type="primary" class="dialog-verification-button green-button"
                         @click="getCode(1)" :disabled="getCodeBtnDisable"
                         :class="{ 'disabled-style': getCodeBtnDisable }">
                {{ btnGetMsgCode }}
              </el-button>
              <!-- <el-button type="primary">发送验证码</el-button> -->
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
              <el-button @click="resetForm('ruleForm')">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <div class="account_card">
      <div class="account_item">
        <div class="account_item_line">
          <div class="account_item_left">
            <i class="el-icon-message account_icon"></i>
            <span class="account_title">手机绑定</span>
          </div>
        </div>
        <div class="email_form_wrap">
          <!--					<div class="account_item_left">-->
          <!--						<i class="el-icon-mobile-phone account_icon"></i>-->
          <!--						<span class="account_title">13888881234</span>-->
          <!--					</div>-->
          <el-form :model="ruleForm2" status-icon :rules="rules2" ref="ruleForm2" label-width="100px"
                   class="demo-ruleForm">
            <el-form-item label="邮箱" prop="email2">
              <el-input v-model="ruleForm2.email2"></el-input>
            </el-form-item>
            <el-form-item label="修改的手机号" prop="phonenumber2">
              <el-input v-model.number="ruleForm2.phonenumber2"></el-input>
            </el-form-item>
            <el-form-item label="邮箱验证码" prop="emailcode">
              <el-input v-model="ruleForm2.emailcode"></el-input>
              <el-button type="primary" class="dialog-verification-button green-button"
                         @click="getCode(2)" :disabled="getCodeBtnDisable2"
                         :class="{ 'disabled-style': getCodeBtnDisable2 }">
                {{ btnGetMsgCode2 }}
              </el-button>
              <!-- <el-button type="primary">发送验证码</el-button> -->
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="submitForm('ruleForm2')">提交</el-button>
              <el-button @click="resetForm('ruleForm2')">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>


<script>
import verifyCode from '@/components/verifyCode.vue'
export default {


  name: "personData",
  data() {
    var checkPhonenumber = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('手机号不能为空'));
      }
    };
    var checkEmail = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('邮箱不能为空'));
      }
    };
    var checkPhonecode = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('验证码不能为空'));
      }
    };
    return {
      tabsActive: 'base',
      emailForm: {
        email: '',
        verifyCode: ''
      },
      identifyCodes: '1234567890abcdef',
      identifyCode: '',
      ruleForm: {
        phonenumber: '',
        email: '',
        phonecode: '',
      },
      ruleForm2: {
        phonenumber2: '',
        email2: '',
        emailcode: '',
      },
      rules: {
        phonenumber: [{
          validator: checkPhonenumber,
          trigger: 'blur'
        }],
        email: [{
          validator: checkEmail,
          trigger: 'blur'
        }],
        phonecode: [{
          validator: checkPhonecode,
          trigger: 'blur'
        }]
      },
      rules2: {
        phonenumber2: [{
          validator: checkPhonenumber,
          trigger: 'blur'
        }],
        email2: [{
          validator: checkEmail,
          trigger: 'blur'
        }],
        emailcode: [{
          validator: checkPhonecode,
          trigger: 'blur'
        }]
      },
      btnGetMsgCode: "获取短信验证码",
      waitTime: 61,
      btnGetMsgCode2: "获取邮件验证码",
      waitTime2: 61,
      uuidEmail: '',
      uuidPhone: ''
    }
  },


  watch: {
    $route: {
      handler() {
        this.tabsActive = this.$route.query.tab;
        console.log("tabsActive::", this.tabsActive);
      },
      deep: true,
    },
  },
  computed: {
    // 用于校验手机号码格式是否正确（登录）
    phoneNumberStyle() {
      let reg = /^1[3456789]\d{9}$/;
      if (!reg.test(this.ruleForm.phonenumber)) {
        return false;
      }
      return true;
    },
    phoneNumberStyle2() {
      let reg = /^\w+@[a-zA-Z0-9]{2,10}(?:\.[a-z]{2,4}){1,3}$/;
      if (!reg.test(this.ruleForm2.email2)) {
        return false;
      }
      return true;
    },
    getCodeBtnDisable: {
      get() {
        if (this.waitTime == 61) {
          if (this.ruleForm.phonenumber) {
            return false;
          }
          return true;
        }
        return true;
      },
      // 注意：因为计算属性本身没有set方法，不支持在方法中进行修改，而下面我要进行这个操作，所以需要手动添加
      set() {},
    },
    getCodeBtnDisable2: {
      get() {
        if (this.waitTime2 == 61) {
          if (this.ruleForm2.email2) {
            return false;
          }
          return true;
        }
        return true;
      },
      // 注意：因为计算属性本身没有set方法，不支持在方法中进行修改，而下面我要进行这个操作，所以需要手动添加
      set() {},
    },
  },
  methods: {
    handleSelect(key, keyPath) { //路由
      this.$router.push({
        name: key,
        params: {
          activityId: "0"
        }
      })
    },
    //跳转到医生认证
    toDoctorCertify() {
      this.$router.push("/doctorCertify");
    },
    submitForm(formName) {
      if (formName == 'ruleForm') {
        this.updateEmail();
      }else{
        this.updatePhone();
      }
      // this.$refs[formName].validate((valid) => {
      //   if (valid) {
      //     alert('submit!');
      //     if (formName == 'ruleForm') {
      //       this.updateEmail();
      //     }else{
      //       this.updatePhone();
      //     }
      //   } else {
      //     console.log('error submit!!');
      //     return false;
      //   }
      // });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    async getCode(num) {
      if (this.phoneNumberStyle || this.phoneNumberStyle2) {
        // 调用获取短信验证码接口
        let res;
        if (num === 1) {
          //登录请求验证码
          res = await this.$api.reqPhoneCode({
            mobile: this.ruleForm.phonenumber,
          });
          if (res.code === 200) {
            this.uuidEmail = res.uuid;
          }
          let that = this;
          that.waitTime--;
          that.getCodeBtnDisable = true;
          this.btnGetMsgCode = `${this.waitTime}s 后重新获取`;
          let timer = setInterval(function() {
            if (that.waitTime > 1) {
              that.waitTime--;
              that.btnGetMsgCode = `${that.waitTime}s 后重新获取`;
            } else {
              clearInterval(timer);
              that.btnGetMsgCode = "获取短信验证码";
              that.getCodeBtnDisable = false;
              that.waitTime = 61;
            }
          }, 1000);
        }else{
          res = await this.$api.reqEmailCode(this.ruleForm2.email2);
          if (res.code === 200) {
            this.uuidPhone = res.uuid;
          }
          let that = this;
          that.waitTime2--;
          that.getCodeBtnDisable2 = true;
          this.btnGetMsgCode2 = `${this.waitTime}s 后重新获取`;
          let timer = setInterval(function() {
            if (that.waitTime2 > 1) {
              that.waitTime2--;
              that.btnGetMsgCode2 = `${that.waitTime2}s 后重新获取`;
            } else {
              clearInterval(timer);
              that.btnGetMsgCode2 = "获取邮件验证码";
              that.getCodeBtnDisable2 = false;
              that.waitTime2 = 61;
            }
          }, 1000);
        }
      }
    },
    async updateEmail() {
      let params = {
        'mobile': this.ruleForm.phonenumber,
        'code': this.ruleForm.phonecode,
        'username': this.ruleForm.email,
        'uuid': this.uuidEmail
      };
      const res = await this.$api.reqAlterEmail(params);
      if(res.code==200){
      	this.$message({
      	  type: "success",
      	  message: "修改成功",
      	});
      }else{
        this.$message({
          type: "fail",
          message: res.msg,
        });
      }
    },
    async updatePhone() {
      let params = {
        'mobile': this.ruleForm2.phonenumber2,
        'code': this.ruleForm2.emailcode,
        'username': this.ruleForm2.email2,
        'uuid': this.uuidPhone
      };
      const res = await this.$api.reqAlterPhone(params);
      if(res.code==200){
      	this.$message({
      	  type: "success",
      	  message: "修改成功",
      	});
      }else{
        this.$message({
          type: "fail",
          message: res.msg,
        });
      }
    }
  },
  mounted() {
    this.identifyCode = ''
    // this.makeCode(this.identifyCodes, 4)
  },
};
</script>

<style lang="scss" scoped>
.breadcrumb_wrap {
  width: 100%;
  height: 40px;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding-left: 10px;
  box-sizing: border-box;

  .current {
    font-size: 14px;
  }
}

.account_card {
  background-color: #fff;
  margin-top: 20px;

  .account_item {
    padding: 30px;
    border-bottom: 1px dashed #ccc;

    .account_item_line {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .account_item_left {
        display: flex;
        align-items: center;

        .account_icon {
          font-size: 26px;
        }

        .account_title {
          color: #909399;
          font-size: 16px;
          margin-left: 15px;
        }
      }
    }

    .email_form_wrap {
      background-color: #f2f2f2;
      width: 500px;
      padding: 30px;
      padding-bottom: 10px;
      margin-top: 10px;
      border-radius: 10px;

      .form_line {
        display: flex;
        align-items: center;

        .verify_code_wrap {
          height: 40px;
          line-height: 40px;
          margin: 0 10px;
          cursor: pointer;
        }
      }
    }
  }

}
</style>
